import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:magic_car/UI/Loading.dart';
import 'package:magic_car/main.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';

//import 'dart:mirrors';
class ExamQuesPage extends StatefulWidget {
  // ExamQuesPage({Key key, this.title}) : super(key: key);

  final String rid;
  final String type;
  ExamQuesPage(this.rid, this.type);
  @override
  _MyHomePageState createState() => new _MyHomePageState(this.rid, this.type);
}

class _MyHomePageState extends State<ExamQuesPage> {
  List formList;
  bool first = true;
  int index = 0;
  int examlength;
  final String rid;
  final String type;
  _MyHomePageState(this.rid, this.type);

  List exam = [];
  Map currentExamp = new Map();
  initState() {
    super.initState();
    formList = [
      {
        "title": '车牌号111111',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
    ];
    loaddata();
  }

//取消考试
  cancel() async {
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["id"] = pref.getString('uid');
    HttpHelper.post(HttpHelper.API_CancelTest, (data) async {
      if (data != null) {
        print(data);

        if (data["code"].toString() == "1") {
        } else {}
      }
    }, params: map);
  }

//完成考试
  finish() async {
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["id"] = pref.getString('uid');
    HttpHelper.post(HttpHelper.API_FinishExam, (data) async {
      if (data != null) {
        print(data);

        if (data["code"].toString() == "1") {
        } else {}
      }
    }, params: map);
  }

  //加载数据
  loaddata() async {
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["rid"] = this.rid;
    map['type'] = this.type;

    print(map);

    HttpHelper.post(HttpHelper.API_CheckQues, (data) async {
      if (data != null) {
        print(data);
        print(data["info"]);
        if (data["code"].toString() == "1") {
          //2020/10/17 如果试题被删除，直接跳过
          List temp = [];
          for (var i = 0; i < data["info"].length; i++) {
            if (data['info'][i]['id'] != null) {
              temp.add(data['info'][i]);
            }
          }
          setState(() {
            exam = temp;
          });
          // setState(() {
          //   exam = data["info"];
          // });
          // List examkey = exam.keys.toList();

          // print(examkey);
          setState(() {
            currentExamp = exam[0];
            examlength = exam.length;
            // currentExamp["useranswer"]=currentExamp['answer'];
            //   currentExamp["useranswer"] = "";
          });
          renamearr();
        } else {
          Toast.show(data["msg"], context);
        }
      }
    }, params: map);
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;

    if (currentExamp.containsKey('id')) {
      //判断是否有题目
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
          child: Container(
              color: Colors.white,
              child: Padding(
                padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
                child: new Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                          padding: new EdgeInsets.fromLTRB(22, 0, 20, 0),
                          child: examtitle()),
                      Padding(
                          padding: new EdgeInsets.fromLTRB(22, 7, 20, 0),
                          child: new Text(
                            "难度：" + currentExamp["level"] + "级",
                            style: TextStyle(
                                color: Color.fromRGBO(103, 103, 103, 1),
                                fontSize: 12),
                          )),
                      Padding(
                          padding: new EdgeInsets.fromLTRB(22, 7, 20, 0),
                          child: Image.network(currentExamp["thumb"])),
                      answer(),
                      index == 0
                          ? new Text("")
                          : Padding(
                              padding: new EdgeInsets.fromLTRB(0, 20, 0, 10),
                              child: Container(
                                padding: new EdgeInsets.fromLTRB(20, 0, 20, 0),
                                height: 50,
                                decoration: new BoxDecoration(
                                    color: Color.fromRGBO(27, 182, 251, 1),
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(5)),
                                    border: new Border.all(
                                        width: 0,
                                        color:
                                            Color.fromRGBO(27, 182, 251, 1))),
                                child: SizedBox(
                                    width: double.infinity,
                                    height: 50,
                                    child: new FlatButton(
                                      child: Text(
                                        '上一题',
                                        style: TextStyle(
                                            color: Colors.white, fontSize: 16),
                                      ),
                                      color: Color.fromRGBO(27, 182, 251, 1),
                                      textColor: Colors.white,
                                      onPressed: () async {
                                        index--;
                                        setState(() {
                                          currentExamp = exam[index];
                                          //currentExamp["useranswer"] = "H";
                                        });
                                        //renamearr();
                                      },
                                    )),
                              )),
                      examlength != index + 1
                          ? Padding(
                              padding: new EdgeInsets.fromLTRB(0, 20, 0, 10),
                              child: Container(
                                padding: new EdgeInsets.fromLTRB(20, 0, 20, 0),
                                height: 50,
                                decoration: new BoxDecoration(
                                    color: Color.fromRGBO(27, 182, 251, 1),
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(5)),
                                    border: new Border.all(
                                        width: 0,
                                        color:
                                            Color.fromRGBO(27, 182, 251, 1))),
                                child: SizedBox(
                                    width: double.infinity,
                                    height: 50,
                                    child: new FlatButton(
                                      child: Text(
                                        '下一题',
                                        style: TextStyle(
                                            color: Colors.white, fontSize: 16),
                                      ),
                                      color: Color.fromRGBO(27, 182, 251, 1),
                                      textColor: Colors.white,
                                      onPressed: () async {
                                        index++;
                                        setState(() {
                                          currentExamp = exam[index];
                                          // currentExamp["useranswer"] = "";
                                        });
                                        renamearr();
                                        // subAns();

                                        // index++;
                                        // setState(() {
                                        //   currentExamp = exam[index.toString()];
                                        //   currentExamp["useranswer"] = "";
                                        // });
                                        // renamearr();
                                      },
                                    )),
                              ))
                          : new Container(height: 0)
                    ]),
              ))));
    }

    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  //提交答案
  subAns() async {
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["uid"] = pref.getString('uid');
    //  map["record_id"] = exam["record_id"];
    map["question_paper_id"] = currentExamp["id"];
    String type = currentExamp["type"];
    String userans = "";
    if (currentExamp.containsKey('useranswer')) {
      userans = currentExamp["useranswer"];
    }

    print(currentExamp);

    if (type == "1") {
      //判断题
      if (userans == "A") {
        userans = "1";
      } else if (userans == "B") userans = "2";
    } else if (type == "3") {
      //多项
      List ans = currentExamp["items"];
      for (var i = 0; i < ans.length; i++) {
        var item = ans[i];
        if (item is String) continue;
        bool selects = item["select"];

        if (selects == true) {
          userans = userans + item["code"];
        }
      }
    }
    map["user_answer"] = userans;
    print(map);
    //return;

    HttpHelper.post(HttpHelper.API_SubexamAns, (data) async {
      //loadpage.close();
      if (data != null) {
        // print(data);
        if (data["code"].toString() == "1") {
          print(index.toString());
          print(examlength.toString());
          if (index == examlength - 2) {
            //已经最后一题
            // _showDialog('考试已完成，是否结束？ ',0);
            showAlert('考试已完成，是否结束？ ', 0);
          } else {
            index++;
            setState(() {
              currentExamp = exam[index];
              // currentExamp["useranswer"] = "";
            });
            renamearr();
          }
        } else {
          Toast.show(data["msg"], context);
        }
      }
    }, params: map);
  }

  showAlert(msg, type) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: 130,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: Center(
                          child: Text(msg, style: TextStyle(fontSize: 16)))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            // Navigator.pop(context);
                            //  confirm();
                            Navigator.pop(context);
                            if (type == 0) {
                              await finish();
                              Navigator.pop(context);
                            } else {
                              await cancel();
                              Navigator.pop(context);
                            }
                          },
                          child: Center(
                              child: Text('确定',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: Center(
                              child:
                                  Text('取消', style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
  }

  _showDialog(msg, type) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text(msg),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                    // Navigator.pop(context);
                  },
                  child:
                      new Text('否', style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                    // Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => MyApp()), (route)=>route==null);
                    // sleep(Duration(seconds: 1));
                    if (type == 1) {
                      cancel();
                    }
                    Navigator.pop(context);
                    finish();

                    // Future.delayed(Duration(seconds: 1), () {
                    //   Navigator.pop(context);
                    // });
                    // Navigator.popAndPushNamed(context, "uindex");
                    // Navigator.pop(context);
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }

  renamearr() {
    if (currentExamp['id'] == null) {
      return;
    }
    // if (currentExamp["type"] == "1") {
    //   currentExamp["items"] = ["正确", "错误"];
    //   setState(() {
    //     currentExamp = currentExamp;
    //   });
    // }
    if (currentExamp["type"] == "1") {
      //判断题
      if (currentExamp["useranswer"] == "1") {
        currentExamp["useranswer"] = "A";
      } else if (currentExamp["useranswer"] == "2") {
        currentExamp["useranswer"] = "B";
      }
    }
    List answers = currentExamp["items"];
    if (currentExamp["type"] == "2" || currentExamp["type"] == "3") {
      List codes = [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
      ];
      for (var i = 0; i < answers.length; i++) {
        var values = answers[i];
        if (values is String) {
          if (values == "") continue;
          if (currentExamp["type"] == "3") {
            Map temp = {"code": codes[i], "value": values, "select": false};
            //contains
            var code = temp["code"];
            //  List<int> bb = currentExamp["useranswer"].codeUnits;
            for (int i = 0; i < currentExamp["useranswer"].length; i++) {
              if (code == currentExamp["useranswer"][i].toString()) {
                temp["select"] = true;
              }
            }
            // if (currentExamp["useranswer"].contains[code]) {
            //   temp["select"] = true;
            // }
            answers[i] = temp;
          } else {
            Map temp = {"code": codes[i], "value": values};
            answers[i] = temp;
          }
        }
      }
    }
    // }
  }

  Widget examtitle() {
    var content;
    var typeStr = "";
    if (currentExamp["type"] == "2") {
      typeStr = "【单选题】";
    } else if (currentExamp["type"] == "3") {
      typeStr = "【多选题】";
    } else if (currentExamp["type"] == "1") {
      typeStr = "【判断题】";
    }
    print('问题');
    print(typeStr + currentExamp["question"]);
    content = new Text(
        (index + 1).toString() + "、" + typeStr + currentExamp["question"]);
    return content;

    //ew Text("[多选题]" + currentExamp["question"]),
  }

  Widget answer() {
    var content;

    List answers;
    print(currentExamp);

    // print(currentExamp);
    //单选,判断
    if (currentExamp["type"] == "2") {
      answers = currentExamp["items"];
      List<Widget> item = [];
      for (var i = 0; i < answers.length; i++) {
        var answer = answers[i];
        if (answer != "") {
          item.add(RadioListTile(
            value: answer["code"],
            groupValue: currentExamp["useranswer"],
            dense: true,
            //selected: answer["select"],
            onChanged: (value) {
              setState(() {
                // Toast.show('选择的答案'+value, context);
                currentExamp["useranswer"] = value;
              });

              // print(currentExamp);
            },
            title: Text(answer["code"] + "：" + answer["value"]),
          ));
        }
      }
      content = new Column(
        children: item,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.start,
      );
    } else if (currentExamp["type"] == "3") {
      answers = currentExamp["items"];
      //currentExamp["useranswer"] = false;
      List<Widget> item = [];
      for (var i = 0; i < answers.length; i++) {
        var answer = answers[i];
        if (answer != "") {
          item.add(CheckboxListTile(
              controlAffinity: ListTileControlAffinity.leading,
              value: answer["select"],
              title: Text(
                answer["code"] + "：" + answer["value"],
                style: TextStyle(color: Colors.black),
              ),
              //subtitle: Text("这是二级标题"),

              selected: answer["select"],
              dense: true,
              onChanged: (value) {
                setState(() {
                  // this.flag = value;
                  answer["select"] = value;
                  if (value == true) {}
                });
              }));
        }
      }
      content = new Column(
        children: item,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.start,
      );
    } else if (currentExamp["type"] == "1") {
      //1212
      // answers = currentExamp["items"];
      List<Widget> item = [];
      item.add(RadioListTile(
        value: "A",
        groupValue: currentExamp["useranswer"],
        dense: true,
        onChanged: (value) {
          setState(() {
            currentExamp["useranswer"] = value;
          });

          // print(currentExamp);
        },
        title: Text("A：正确"),
      ));
      item.add(RadioListTile(
        value: "B",
        dense: true,
        groupValue: currentExamp["useranswer"],
        onChanged: (value) {
          setState(() {
            currentExamp["useranswer"] = value;
          });

          // print(currentExamp);
        },
        title: Text("B：错误"),
      ));
      // for (var i = 0; i < answers.length; i++) {
      //   var answer = answers[i];
      //   if (answer != "") {
      //     item.add(RadioListTile(
      //       value: answer["code"],
      //       groupValue: currentExamp["useranswer"],
      //       onChanged: (value) {
      //         setState(() {
      //           currentExamp["useranswer"] = value;
      //         });

      //         // print(currentExamp);
      //       },
      //       title: Text(answer["code"] + "：" + answer["value"]),
      //     ));
      //   }
      // }
      content = new Column(
        children: item,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.start,
      );
    }
    return new Padding(
      padding: new EdgeInsets.fromLTRB(0, 10, 0, 0),
      child: content,
    );
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          titleSpacing: 0,
          title: new Text('考试',style: TextStyle(fontSize: Config.title_size),),
          backgroundColor: Colors.white,
          elevation: 0,
        ),
        body: new Center(
          child: Container(
              decoration: new BoxDecoration(
                color: Color.fromRGBO(238, 238, 238, 1),
              ),
              child: new ListView(
                children: <Widget>[buildcontent()],
              )),
        ));
  }

  Future<bool> willpop() {
    showAlert('确认退出考试？退出之后，需要重新开始', 1);
    //_showDialog('确认退出考试？退出之后，需要重新开始',1);
    return Future.value(false);
  }
}
